package cn.skylark.wcm.common.config.druid;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSource;

/**
 * Druid的DataResource配置类
 *
 * @author chuhl
 * @since 2017年12月4日14:14:18
 */
@Configuration
@EnableTransactionManagement
public class DruidDataSourceConfig implements EnvironmentAware {
  /**
   * Logger
   */
  private Logger logger = LoggerFactory.getLogger(DruidDataSourceConfig.class);
  /**
   * RelaxedPropertyResolver
   */
  private RelaxedPropertyResolver propertyResolver;

  /**
   * 配置文件对于配置项取得
   *
   * @param env org.springframework.core.env.Environment
   */
  @Override
  public void setEnvironment(Environment env) {
    this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
  }

  /**
   * 数据源设定
   *
   * @return datasource
   */
  @Bean
  public DataSource dataSource() {
    logger.info("注入druid开始！！！");
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(propertyResolver.getProperty("url"));
    datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
    datasource.setUsername(propertyResolver.getProperty("username"));
    datasource.setPassword(propertyResolver.getProperty("password"));
    datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
    datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
    datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
    datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
    datasource.setMinEvictableIdleTimeMillis(
            Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
    try {
      datasource.setFilters("stat,wall");
    } catch (SQLException e) {
      e.printStackTrace();
    }
    logger.info("注入druid结束！！！");
    return datasource;
  }
}
